<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="76px">
        <!-- <el-form-item label="作业类别">
          <el-select
            v-model="searchParam.taskKind"
            placeholder="请选择作业类别"
            :disabled="props.taskKind !== '' && props.taskKind !== null"
            @change="changeTaskKind"
            clearable
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="item in useDictionary('EamTaskKind')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="作业类型">
          <el-select
            v-model="searchParam.sopTypeId"
            placeholder="请选择作业类型"
            :disabled="!(sopType !== null)"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.sopTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备种类">
          <el-tree-select
            v-model="searchParam.equipTypeId"
            node-key="id"
            :check-strictly="true"
            :props="{
              children: 'nodes',
              label: 'assetTypeName',
            }"
            placeholder="请选择设备种类"
            :data="deviceList"
            filterable
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="作业名称">
          <el-input
            v-model="searchParam.standardName"
            placeholder="请输入作业名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="作业区域" prop="locationId">
          <el-tree-select
            placeholder="请输入作业区域"
            filterable
            v-model="searchParam.locationId"
            :data="locationInfoTree"
            node-key="id"
            clearable
            :props="{ label: 'locationName', children: 'nodes' }"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column
          v-if="props.assetKind == 3"
          label="物料编号"
          prop="standardCode"
          min-width="180"
          show-overflow-tooltip
        /> -->
        <!--        <el-table-column-->
        <!--          v-if="props.assetKind != 3"-->
        <!--          label="作业编号"-->
        <!--          prop="standardCode"-->
        <!--          min-width="180"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="标准名称"
          prop="standardName"
          min-width="200"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          label="作业类别"
          align="center"
          prop="taskKind"
          min-width="120"
        >
          <template #default="scope">
            <el-tag
              :type="
                scope.row.taskKind == '1'
                  ? 'success'
                  : scope.row.taskKind == '2'
                  ? ''
                  : scope.row.taskKind == '3'
                  ? 'warning'
                  : 'info'
              "
              >{{ useDictionary("EamTaskKind", scope.row.taskKind) }}</el-tag
            >
          </template>
        </el-table-column> -->
        <el-table-column
          label="标准类型"
          prop="sopTypeName"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="props.assetKind == 3"
          label="类型编号"
          prop="assetTypeCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备种类"
          prop="assetTypeName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="作业区域"
          prop="locationName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="标准周期"
          prop="standardCycle"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span
              >{{ scope.row.standardCycle }}
              {{
                useDictionary("StandardCycleType", scope.row.standardCycleType)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="标准人员类型"
          prop="standardPersonnel"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>
              {{
                useDictionary("StandardPersonnel", scope.row.standardPersonnel)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="assetKind != 1"
          label="编制时间"
          prop="standardCompileTime"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="assetKind != 1"
          label="编制人"
          prop="standardCompilePersonnel"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="assetKind != 1"
          label="审核时间"
          prop="standardExamineTime"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="assetKind != 1"
          label="审核人"
          prop="standardExaminePersonnel"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="assetKind != 1"
          label="批准时间"
          prop="standardRatifyTime"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="assetKind != 1"
          label="批准人"
          prop="standardRatifyPersonnel"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="是否启用"
          align="center"
          prop="enabled"
          min-width="100"
        >
          <template #default="scope">
            <el-tag v-show="scope.row.enabled === 1" type="success">是</el-tag>
            <el-tag v-show="scope.row.enabled !== 1" type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="110">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogAllDetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="标准"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="jumpUrl(scope.row)"
              >
                <i-ep-tickets />
              </el-button>
            </el-tooltip>
            <el-dropdown class="ml-[12px] align-middle!">
              <span
                class="el-dropdown-link text-[12px] c-[#409eff] cursor-pointer"
              >
                <i-ep-more class="text-[14px]!" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openDialogDetail(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item @click="openDialog(scope.row)"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item @click="deleteItem(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <common-work-standard-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :assetKind="assetKind"
      :sopTypeCode="props.sopTypeCode"
      :taskKind="taskKind"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <common-work-standard-detail
      :visible="detailDialog.visible"
      :title="detailDialog.title"
      :data="detailDialog.data"
      :assetKind="assetKind"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="detailDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import { ArrowDown } from "@element-plus/icons-vue";
import { getStandardDevicesApi, getStandardTypesApi } from "@/utils/commonData";
import request from "@/utils/request";
import router from "@/router";

defineOptions({
  name: "CommonWorkStandard",
  inheritAttrs: false,
});

const props = defineProps({
  assetKind: {
    type: Number,
    default: null,
  },
  taskKind: {
    type: String,
    default: null,
  },
  sopTypeCode: {
    type: String,
    default: null,
  },
});

const { assetKind, taskKind } = toRefs(props);

// 请求参数
const requestApi = "/eam/eamsopstandard/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  standardCode: "",
  standardName: "",
  sopTypeId: "",
  taskKind: taskKind.value,
  equipTypeId: "",
  brandId: "",
  locationId: "",
  assetKind: assetKind.value,
};

const deleteParam = {
  api: "/eam/eamsopstandard/delete",
  data: {
    assetKind: assetKind.value,
  },
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  // reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);
const reset = () => {
  searchParam.value.standardName = "";
  searchParam.value.sopTypeId = "";
  searchParam.value.locationId = "";
  searchParam.value.equipTypeId = "";
  getTableList();
};

const sopType = ref();
onMounted(async () => {
  await getTypeList("");
  await getLocationInfoTree();
  if (props.taskKind) {
    searchParam.value.taskKind = props.taskKind;
  }
  if (props.sopTypeCode) {
    sopType.value = typeList.value.find(
      (item: any) => item.sopTypeCode === props.sopTypeCode
    );
    searchParam.value.sopTypeId = sopType.value?.id;
  }
  getDeviceList();
  getTableList();
});

// 查看弹窗所有信息
const detailDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查看弹窗 弹出
function openDialogAllDetail(roleObj?: any) {
  detailDialog.title = "详情";
  getAllInfo(roleObj.id);
  detailDialog.readvisible = true;
}
// 查看弹窗 获取详情
async function getAllInfo(id: string) {
  request({
    url: `/eam/eamsopstandard/get/${id}`,
    method: "get",
    data: {
      assetKind: assetKind.value,
    },
  })
    .then((data) => {
      detailDialog.data = data.data;
      detailDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

// 编辑弹窗所有信息
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamsopstandard/get/${id}`,
    method: "get",
    data: {
      assetKind: assetKind.value,
    },
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开标准标准规程表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改标准规程";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增标准规程";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开标准标准规程表单弹窗 详情 */
function openDialogDetail(roleObj?: any) {
  addDialog.title = "标准规程详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  detailDialog.visible = value;
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    detailDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamsopstandard/deleteItem/${id}`,
      method: "post",
      data: {
        assetKind: assetKind.value,
      },
    });
    search();
  });
}

// 获取标准类型列表
const typeList = ref(<any>[]);
async function getTypeList(value: string) {
  const params = {
    taskKind: props.taskKind,
    assetKind: props.assetKind,
  };
  typeList.value = (await getStandardTypesApi(params)) ?? [];
}

// 标准类别变更事件
function changeTaskKind(value: string) {
  typeList.value = [];
  searchParam.value.sopTypeId = "";
  getTypeList(value);
}

// 标准项页面跳转
function jumpUrl(row: any) {
  router.push({
    name: "EAMEQUEAMSOPITEM",
    query: { id: row.id, assetKind: assetKind.value },
  });
}
// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
// 获取保养类型列表
const deviceList = ref(<any>[]);
async function getDeviceList() {
  const params = {
    assetKind: 1,
  };
  deviceList.value = (await getStandardDevicesApi(params)) ?? [];
}
</script>
<style lang="scss"></style>
